import React, { createContext, useContext, useState, useEffect } from 'react';

const AuthContext = createContext();

export const useAuth = () => {
  const context = useContext(AuthContext);
  if (!context) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};

export const AuthProvider = ({ children }) => {
  const [currentUser, setCurrentUser] = useState(null);
  const [loading, setLoading] = useState(true);

  // 模拟成员数据
  const mockMembers = [
    {
      id: 1,
      name: '张三',
      username: 'zhangsan',
      password: 'password123',
      role: '主唱',
      accountRole: 'user',
      accountStatus: 'active',
      avatar: 'https://joeschmoe.io/api/v1/1',
      email: 'zhangsan@example.com',
      lastLogin: '2024-01-18 14:30',
      loginCount: 45,
    },
    {
      id: 2,
      name: '李四',
      username: 'lisi',
      password: 'password123',
      role: '吉他手',
      accountRole: 'admin',
      accountStatus: 'active',
      avatar: 'https://joeschmoe.io/api/v1/2',
      email: 'lisi@example.com',
      lastLogin: '2024-01-19 09:15',
      loginCount: 128,
    },
    {
      id: 3,
      name: '王五',
      username: 'wangwu',
      password: 'password123',
      role: '贝斯手',
      accountRole: 'user',
      accountStatus: 'inactive',
      avatar: 'https://joeschmoe.io/api/v1/3',
      email: 'wangwu@example.com',
      lastLogin: '2024-01-10 16:45',
      loginCount: 23,
    },
    {
      id: 4,
      name: '赵六',
      username: 'zhaoliu',
      password: 'password123',
      role: '鼓手',
      accountRole: 'user',
      accountStatus: 'active',
      avatar: 'https://joeschmoe.io/api/v1/4',
      email: 'zhaoliu@example.com',
      lastLogin: '2024-01-17 11:20',
      loginCount: 67,
    },
    {
      id: 5,
      name: '钱七',
      username: 'qianqi',
      password: 'password123',
      role: '键盘手',
      accountRole: 'user',
      accountStatus: 'active',
      avatar: 'https://joeschmoe.io/api/v1/5',
      email: 'qianqi@example.com',
      lastLogin: '2024-01-16 13:55',
      loginCount: 89,
    },
  ];

  // 检查本地存储中的登录状态
  useEffect(() => {
    const savedUser = localStorage.getItem('currentUser');
    if (savedUser) {
      try {
        setCurrentUser(JSON.parse(savedUser));
      } catch (error) {
        console.error('Failed to parse saved user:', error);
        localStorage.removeItem('currentUser');
      }
    }
    setLoading(false);
  }, []);

  // 纯前端登录函数
  const login = async (username, password) => {
    // 模拟API延迟
    await new Promise(resolve => setTimeout(resolve, 500));
    
    // 从模拟数据中查找用户
    const mockUser = mockMembers.find(m => 
      m.username === username && 
      m.password === password && 
      m.accountStatus === 'active'
    );
    
    if (mockUser) {
      const userSession = {
        id: mockUser.id,
        username: mockUser.username,
        name: mockUser.name,
        role: mockUser.role,
        accountRole: mockUser.accountRole,
        avatar: mockUser.avatar,
        email: mockUser.email,
        loginTime: new Date().toISOString(),
      };
      
      setCurrentUser(userSession);
      localStorage.setItem('currentUser', JSON.stringify(userSession));
      localStorage.setItem('token', 'mock-token-' + Date.now());
      console.log('Login successful for:', mockUser.name);
      return true;
    }
    
    return false;
  };

  // 纯前端登出函数
  const logout = () => {
    setCurrentUser(null);
    localStorage.removeItem('currentUser');
    localStorage.removeItem('token');
    console.log('Logout successful');
  };

  // 检查用户是否已登录
  const isAuthenticated = () => {
    return currentUser !== null;
  };

  // 检查用户权限
  const hasRole = (role) => {
    return currentUser && currentUser.accountRole === role;
  };

  // 检查是否为管理员
  const isAdmin = () => {
    return hasRole('admin');
  };

  // 更新用户信息
  const updateUser = (updates) => {
    if (currentUser) {
      const updatedUser = { ...currentUser, ...updates };
      setCurrentUser(updatedUser);
      localStorage.setItem('currentUser', JSON.stringify(updatedUser));
    }
  };

  // 获取所有成员数据
  const getAllMembers = () => {
    return mockMembers;
  };

  // 更新成员数据
  const updateMember = (memberId, updates) => {
    console.log(`Update member ${memberId}:`, updates);
    
    // 如果更新的是当前用户，同时更新当前用户状态
    if (currentUser && currentUser.id === memberId) {
      updateUser(updates);
    }
  };

  // 删除成员
  const deleteMember = (memberId) => {
    console.log(`Delete member ${memberId}`);
    
    // 如果删除的是当前用户，登出
    if (currentUser && currentUser.id === memberId) {
      logout();
    }
  };

  // 重置密码
  const resetPassword = (memberId) => {
    console.log(`Reset password for member ${memberId}`);
  };

  const value = {
    currentUser,
    login,
    logout,
    isAuthenticated,
    hasRole,
    isAdmin,
    updateUser,
    loading,
    getAllMembers,
    updateMember,
    deleteMember,
    resetPassword,
  };

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  );
}; 